#include "../inc/group_chat.h"


bool Broadcast_Task(PCN client_node)
{

    printf("专门为%s客户端广播服务!\n", client_node->cli_ip);

    char msg[MSG_MAX_LEN];
    char package[MSG_MAX_LEN];
    while (1)
    {
        memset(msg, 0, MSG_MAX_LEN);
        int read_ret = read(client_node->cli_fd, msg, MSG_MAX_LEN);
        if (read_ret == -1)
        {
            perror("read ...");
            return false;
        }
        else if (read_ret == 0)
        {
            printf("%s下线！333\n", client_node->cli_ip);

            // 当前客户端掉线了
            // 上锁
            pthread_mutex_lock(&(client_node->ser_info->mutex));

            if (Del_Client_Node(client_node) == false)
            {
                printf("删除下线客户端结点失败！\n");
                // 解锁
                pthread_mutex_unlock(&(client_node->ser_info->mutex));

                pthread_exit((void *)-1); // 线程退出
            }

            pthread_mutex_unlock(&(client_node->ser_info->mutex));
            // 解锁

            free(client_node); // 释放当前客户端结点堆空间
            break;
        }
        else
        {
            // 有数据信息进行遍历链表广播给其它客户端 SEND_MODE_BASE：普通广播模式：避免自己，给其他人广播
            if (strcmp(msg, EXIT_MASK) == 0)
            {
                printf("%s退出群聊！\n", client_node->cli_ip);

                break;
            }

            strcat(package, client_node->cli_ip);
            strcat(package, "说：");
            strcat(package, msg);
            if (Send_All(client_node, package, SEND_MODE_BASE) == false)
            {
                printf("发送广播消息失败！\n");
                return false;
            }
            memset(package, 0, sizeof(package));
        }
    }

    // 线程正常退出
    return true;
}

bool Send_All(PCN client_node, char *broadcast_msg, int send_mode)
{

    PCN client_head; // 后面用来保存链表的头节点

    if (send_mode == SEND_MODE_BASE) // 如果你是普通广播client_head等于
    {
        client_head = client_node->ser_info->cli_node_head;
    }

    if (send_mode == SEND_MODE_EXIT)
    {
        client_head = client_node;
    }

    for (PCN tmp_client_node = client_head->next;
         tmp_client_node != client_head;
         tmp_client_node = tmp_client_node->next)
    {
        if (send_mode == SEND_MODE_BASE)
        {
            if (tmp_client_node->cli_fd != client_node->cli_fd)
            {
                // 实现发送广播消息

                if (write(tmp_client_node->cli_fd, broadcast_msg, strlen(broadcast_msg)) == -1)
                {
                    perror("write ...");
                    return false;
                }
            }
        }

        if (send_mode == SEND_MODE_EXIT)
        {
            // 实现发送广播消息
            if (write(tmp_client_node->cli_fd, broadcast_msg, strlen(broadcast_msg)) == -1)
            {
                perror("write ...");
                return false;
            }
        }
    }
    return true;
}